package cn.springcloud.fix.demo.thread;

/**
 * 生产者和消费者,线程间通信
 * https://crossoverjie.top/%2F2018%2F03%2F16%2Fjava-senior%2Fthread-communication%2F
 */
public class ThreadTest {

    private static boolean empty = true;
    private static int count = 0;

    public static void main(String[] args) {
        Object o = new Object();

        new Thread(() -> {
            while (count <= 100) {
                synchronized (o) {
                    count++;
                    if (empty) {
                        System.out.println("开始生产");
                        empty = false;
                        o.notify();//通知消费者消费
                    } else {
                        try {
                            System.out.println("等消费掉了再生产");
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "A").start();

        new Thread(() -> {
            while (count <= 100) {
                synchronized (o) {
                    count++;
                    if (empty) {
                        try {
                            System.out.println("空的怎么消费？");
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("已经消费掉了");
                        empty = true;
                        o.notify();//通知生产者生产
                    }
                }
            }
        }, "B").start();
    }
}
